let http = require('http');
let querystring = require('querystring');
let crypto = require('crypto');

let sign = (value) => {
  return crypto.createHmac('sha256', 'zb')
    .update(value.toString())
    .digest('base64')
    .replace(/[+/]/g, '');
}
http.createServer(function (req, res) {
  let arr = [];
  res.setCookie = function (key, value, options = {}) {
    let optionsArr = [];

    if (options.maxAge) {
      optionsArr.push(`Max-age=${options.maxAge}`)
    }
    if (options.path) {
      optionsArr.push(`path=${options.path}`)
    }
    if (options.httpOnly) {
      optionsArr.push(`httpOnly=${options.httpOnly}`)
    }
    if (options.signed) {
      value = value + '.' + sign(value);
    }
    arr.push(`${key}=${value}; ` + optionsArr.join('; '));
    res.setHeader('Set-Cookie', arr);
  }
  res.getCookie = function (key) {
    let cookies = querystring.parse(req.headers.cookie, '; ') || {};
    return cookies[key];
  }
  res.getSignCookie=function (key) {
    let cookies = querystring.parse(req.headers.cookie, '; ') || {};
    if (cookies[key]){
      let[value,signValue]=cookies.split('.');
      if (sign(value)===signValue){
        return value;
      }
    }

    return  '';

  }
  if (req.url === '/read') {
    let cookies = querystring.parse(req.headers.cookie, '; ') || {};
    res.end(res.getCookie('hello'));

  }
  if (req.url === '/write') {
    res.setHeader('Set-Cookie', 'name=zb');
    res.setHeader('Set-Cookie', ['age=8', 'name=gyn',
      'domain=.localhost', 'path=/read',
      'expires=' + new Date(Date.now() + 10000).toUTCString(),
      'httpOnly=true',

    ]);
    res.setCookie('hello', 'hehe');

    res.end('ok')

  }
}).listen(3000);


// 签名
let secret = 'zb';


let str = crypto.createHmac('sha1', secret).update('123456').digest('base64');

// let str = crypto.createHash('md5').update('1234').digest('base64');

console.log(str);
